package com.qf.utils;
import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.*;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;

@ConfigurationProperties(prefix = "qiniu")
@Component
@Data
public class QiNiuTools {

    private String accesskey;
    private String secketkey;
    private String bucket;//空间名
    private String url;//外链域名

    public String upload(MultipartFile file) { //mvc提供的上传解析器，file就是上传对象
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = UUID.randomUUID().toString();

        try {
            //把上传对象转为字节数组
            byte[] uploadBytes = file.getBytes(); //"hello qiniu cloud".getBytes("utf-8");
            Auth auth = Auth.create(accesskey, secketkey);
            String upToken = auth.uploadToken(bucket);
            //使用工具类实现上传
            Response response = uploadManager.put(uploadBytes, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);

            return url+key;//返回外链地址+图片名称
        } catch (Exception ex) {
            //ignore
            ex.printStackTrace();
        }
        return "";
    }
}
